# coding : UTF-8

import subprocess
import argparse
from Bio.Blast import NCBIXML

import sys
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

parse = argparse.ArgumentParser()
parse.add_argument('-seq', type=str, default='None', help="the input sequences")
parse.add_argument('-evalue', type=str, default='0.001', help='Expectation value (E) threshold for saving hits')
parse.add_argument('-db', type=str, default='ZFEA_lncRNA', help='BLAST database name')
parse.add_argument('-wordsize', type=str, default='7', help='Word size for wordfinder algorithm (length of best perfect match)')
parse.add_argument('-maxtargetseq', type=str, default='100', help='Maximum number of aligned sequences to keep')


args = parse.parse_args()
fasta_seq = args.seq
e_value = args.evalue
database = args.db
word_size = args.wordsize
max_target_seq = args.maxtargetseq

fasta_seq = fasta_seq.strip()
fasta_seq = fasta_seq.replace("EE", "\n")
dbdict = {"all_transcripts":"all_trans/all_trans", "ZFEA_lncRNA":"zfea_lncRNA/zfea_lncRNA"}

database = "/var/www/html/primer/Public/db/" + dbdict[database]
program = '/data1/exec/ncbi-blast-2.2.28/bin/blastn'
out_xml = '/var/www/html/primer/Public/data/test.xml'

# print(args)
# print(fasta_seq)
# print(e_value)
# print(database)
# print(word_size)
# print(max_target_seq)

# print(database)

cmd = program + ' -evalue ' + e_value + ' -db ' + database + ' -num_threads 4 ' + ' -word_size ' + word_size + ' -query -' + ' -max_target_seqs ' + max_target_seq + ' -outfmt 5 -out ' + out_xml
cmd = 'echo "' + fasta_seq + '" |' + cmd
# print(cmd)

rc = subprocess.call(cmd, shell=True)
result_handle = open(out_xml)
blast_records = NCBIXML.parse(result_handle)

E_VALUE_THRESH = 0.04
desc = '''
<div class="summary">
<div class="container">

<h1> Results:</h1>

</div>
</div>

<table class="table table-condensed" id="blast_desc">
    <thead>
        <tr>
            <th>Query</th>
            <th>Sbjct</th>
            <th>Subject length</th>

            <th>Score</th>
            <th>Query cover</th>
            <th>E value</th>
            <th>Ident(%) </th>

        </tr>
    </thead>
    <tbody>
'''
align = '<div id=blast_alignment>'
for blast_record in blast_records:
    query = blast_record.query
    query_sp = query.split()
    query_id = query_sp[0]
    for alignment in blast_record.alignments:
        num_matches = len(alignment.hsps)
        title = alignment.title
        title_split = title.split()
        title_id = title_split[0]
        title_seq_id = title_split[1]
        length = alignment.length

        align += '''
            <div id=''' + title_id + ''' class="panel panel-info" >
                <div class="panel-heading">
                    <div class="panel-title">
                        <div class="row">
                            <div class="col-md-10">
                                <label for="">alignment </label>
                            </div>
                            <div class="col-md-2" style="align:right">

                            </div>
                        </div>
                    </div>
                </div>
            <div class="panel-body">
                <p ><b>Query: ''' + blast_record.query + '''</b></p>
                <p><b>Sequence ID:</b><a target="_blank" href="http://songyanglab.sysu.edu.cn/django/zfea/information/tran/''' + title_seq_id + '''/"> ''' + title_seq_id + ' </a><b>Length:</b> ' + str(
            length) + ' <b>Number of Matches:</b> ' + str(num_matches) + '''</p>
            '''
        for hsp in alignment.hsps:
            if hsp.expect < E_VALUE_THRESH:
                score = hsp.score
                bits = hsp.bits
                identities = hsp.identities
                query_start = hsp.query_start
                sbjct_start = hsp.sbjct_start
                e_value = hsp.expect
                query = hsp.query
                match = hsp.match
                sbjct = hsp.sbjct
                align_length = hsp.align_length
                ident = round(identities / align_length * 100, 2)
                ident = str(ident) + '%'
                gap_per = round(hsp.gaps / align_length * 100, 2)
                gap_per = str(gap_per) + '%'
                query_cover = round(align_length / blast_record.query_length * 100, 2)
                query_cover = str(query_cover) + '%'
                desc += '''
                    <tr>
                        <td>''' + query_id + '''</td>
                        <td > <a href="#''' + title_id + '">' + title_seq_id + '''</a></td>
                        <td>''' + str(length) + '''</td>

                        <td>''' + str(score) + '''</td>
                        <td>''' + query_cover + '''</td>
                        <td>''' + str(e_value) + '''</td>
                        <td>''' + ident + '''</td>
                    </tr>
                '''

                align += '''<div class="row"><div class="col-md-6">
                        <table class="table table-condensed ">
                         <caption align="left"> ''' + '''Range ''' + str(
                    alignment.hsps.index(hsp) + 1) + ': ' + str(hsp.sbjct_start) + ' to ' + str(
                    hsp.sbjct_start + align_length - 1) + '''</caption>
                        <thead>
                        <tr>
                            <th>Score</td>
                            <th>Bits</td>
                            <th>Expect</th>
                            <th>Identities</th>
                            <th>Gaps</th>
                            <th>Strand</th>
                        </tr>
                        </thead>
                        <tbody>
                        '''
                align += '''
                        <tr>
                            <td>''' + str(score) + '''</td>
                            <td>''' + str(hsp.bits) + '''</td>

                            <td>''' + str(e_value) + '''</td>
                            <td>''' + str(identities) + '/' + str(align_length) + '(' + ident + ''')</td>
                            <td>''' + str(hsp.gaps) + '/' + str(align_length) + '(' + gap_per + ''')</td>
                            <td>''' + '' + '''</td>

                        </tr>
                        </tbody>
                        </table>
                        </div></div>
                '''
                loops = round(align_length // 60 + 1)
                align += '<pre style="font-family:Courier New">'
                for i in range(0, loops):
                    align += "Query %8s  %s %s\n" % (str(query_start), query[(i * 60):((i + 1) * 60)],
                                                     str(query_start + len(query[(i * 60):((i + 1) * 60)]) - 1))
                    align += "      %8s  %s\n" % ('', match[(i * 60):((i + 1) * 60)])
                    align += "Sbjct %8s  %s %s\n\n" % (str(sbjct_start), sbjct[(i * 60):((i + 1) * 60)], str(
                        sbjct_start + len(sbjct[(i * 60):((i + 1) * 60)]) - 1))
                    query_start += 60
                    sbjct_start += 60
                align += '</pre>'

        align += '</div></div>'
desc += '</tbody></table>'
align += '</div>'
html = '<div class="col-sm-offset-0 col-sm-12">' + desc + align + '</div>'

print(html)